<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.typeCode" placeholder="请输入字典代码" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.typeName" placeholder="请输入名称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
        @click="handleDownload">
        导出
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        密码
      </el-checkbox>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="60"
        :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字典代码" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.typeCode }}</span>
        </template>
      </el-table-column>

      <el-table-column label="类型名称" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.typeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="值编号" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.valueId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="值名称" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.valueName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者编号" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改者编号" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.modifyBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" width="80px" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.modifyDate }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!-- <el-button v-if="row.status!='Y'" size="mini" type="success"
						@click="handleModifyStatus(row,row.status)">
						启用
					</el-button>
					<el-button v-if="row.status!='N'" size="mini" @click="handleModifyStatus(row,row.status)">
						禁用
					</el-button> -->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <!-- 抽屉模态框 -->
    <!-- 抽屉模态框 -->
    <el-drawer :title="dr_title" :visible.sync="dialog" :before-close="handleClose" direction="rtl"
      custom-class="demo-drawer" size="35%">
      <div class="demo-drawer__content">
        <el-form :model="form" ref="form" :rules="rules">
          <el-form-item v-if='show_id_item' label="编号ID" :label-width="formLabelWidth">
            <el-input v-model="form.id" :readonly='true'></el-input>
          </el-form-item>
          <el-form-item label="字典代码" :label-width="formLabelWidth" prop="typeCode">
            <el-input v-model="form.typeCode"></el-input>
          </el-form-item>
          <el-form-item label="类型名称" :label-width="formLabelWidth" prop="typeName">
            <el-input v-model="form.typeName"></el-input>
          </el-form-item>
          <el-form-item label="值编号" :label-width="formLabelWidth" prop="valueId">
            <el-input v-model="form.valueId"></el-input>
          </el-form-item>
          <el-form-item label="值名称" :label-width="formLabelWidth" prop="valueName">
            <el-input v-model="form.valueName"></el-input>
          </el-form-item>


        </el-form>
        <div class="demo-drawer__footer">
          <el-button icon="el-icon-error" @click="cancelForm">取 消</el-button>
          <el-button icon="el-icon-refresh-right" type="warning" @click="resetForm('form')">重置</el-button>
          <el-button icon="el-icon-check" type="success" @click="handleClose('form')"
            :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>



    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    del,
    updateStatus,
    uploadImg,
    add,
    update,
    fetchPv,
    createArticle,
    updateArticle
  } from '@/api/dictApi';
  import {
    fetchDictList
  } from '@/api/dictApi';

  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  export default {
    name: 'ComplexTable',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          Y: 'success',
          N: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNo: 1,
          pageSize: 20,
          userCode: '',
          userName: '',
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],

        sortOptions: [{
          label: 'ID Ascending',
          key: '+id'
        }, {
          label: 'ID Descending',
          key: '-id'
        }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          type: '',
          status: 'published'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          userCode: [{
            required: true,
            message: '用户编号不能为空！',
            trigger: 'blur'
          }],
          userName: [{
            required: true,
            message: '用户名称不能为空！',
            trigger: 'blur'
          }],
          userType: [{
            required: true,
            message: '请选择用户类型！',
            trigger: 'change'
          }],
          userPassword: [{
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          }],
          picPath: [{
            required: true,
            message: '图片不能为空',
            trigger: 'blur'
          }]
        },
        downloadLoading: false,
        dialog: false,
        loading: false,
        form: {
          id: '',
          typeCode: '',
          typeName: '',
          valueId: '',
          valueName: '',
          createBy: '',
          createDate: '',
          modifyBy: '',
          modifyDate: ''
        },
        formLabelWidth: '80px',
        dr_title: '',
        show_id_item: false,
        dictList: [],
        picUrl: '',
        loginUid: localStorage.getItem('uId')
      }
    },
    created() {
      this.getList()
    },
    mounted() {
      this.queryDict();
    },
    methods: {
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(res => {
          console.info('response==>', res)
          this.list = res.data.records;
          this.total = res.data.total;

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      /* 格式状态 */
      statusFormatter(row, column, cellValue, index) {
        return cellValue == 'Y' ? '已启用' : '已禁用';
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, _status) {
        console.info('row=>', row)
        console.info('status=>', status);
        this.$confirm('此操作将更改编号为' + row.id + '的数据状态, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus({
            id: row.id,
            status: _status
          }).then(res => {
            if (res.code == '201') {
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              });
            }

          }).catch(err => {
            this.$message({
              type: 'error',
              message: '操作异常，请联系管理员！'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      sortChange(data) {
        const {
          prop,
          order
        } = data;
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.dr_title = '新增数据';
        this.dialog = true;
        this.show_id_item = false;
        this.clearFormData();
        /* this.resetTemp()
        this.dialogStatus = '新增'
        this.dialogFormVisible = true
        this.$nextTick(() => {
        	this.$refs['dataForm'].clearValidate()
        }) */
      },
      // 清空表单数据
      clearFormData() {
        this.form = {
          id: '',
          typeCode: '',
          typeName: '',
          valueId: '',
          valueName: ''
        }
        this.picUrl = '';
      },
      // 重置
      resetForm() {
        this.clearFormData();
      },

      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.dr_title = '编辑数据';
        this.dialog = true;
        this.show_id_item = true;
        console.info('row=>', row);
        this.clearForm();
        this.form = {
          id: row.id,
          typeCode: row.typeCode,
          typeName: row.typeName,
          valueId: row.valueId,
          valueName: row.valueName
        }

        /* this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = '编辑'
        this.dialogFormVisible = true
        this.$nextTick(() => {
        	this.$refs['dataForm'].clearValidate()
        }) */
      },
      /* 文件上传 */
      handleUpload(e) {
        /* hack判断当前文件是否为空 */
        let files = e.target.files || e.dataTransfer.files;
        if (!files.length) return;

        /* 创建一个form对象 */
        let formData = new FormData();
        formData.append('multipartFile', files[0]); // 添加到form对象中
        console.info('res=>', formData);
        console.info('files[0=>', files[0]);

        uploadImg(formData)
          .then(res => {
            console.info('res=>', res);
            this.form.picPath = res.data;
            this.picUrl = res.data;
          })
          .catch(err => {
            console.info('err=>', err);
          })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData
              .timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        this.$confirm('此操作将永久删除编号为' + row.id + '的数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(row.id).then(res => {
            if (res.code == '201') {
              this.$message({
                message: res.msg,
                type: 'success'
              });
            } else {
              this.$message.error(res.msg);
            }
          }).catch(err => {
            console.error(err);
            this.$message.error('操作异常，请联系管理员！');
          })

          this.list.splice(index, 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['用户编码', '用户名称', '用户类型', '创建时间', '状态']
          const filterVal = ['userCode', 'userName', 'userType', 'creationDate', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '管理员管理'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      handleClose(formName) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$confirm('确定要提交表单吗？')
              .then(() => {
                this.loading = true;
                if (this.form.id == '') {
                  this.insert();
                } else {
                  this.edit();
                }
                this.loading = false;
                this.dialog = false;
              })
              .catch((err) => {
                console.log('error submit!!');
              });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      cancelForm() {
        this.loading = false;
        this.dialog = false;
        clearTimeout(this.timer);
      },
      // 加载字典表中的用户类型数据
      queryDict() {
        fetchDictList('USER_TYPE').then(res => {
          if (res.code == '200') {
            this.dictList = res.data;

          }
        }).catch(err => {
          console.info(err);
        })
      },

      formatDate(date) {
        let yyyy = date.getFullYear();
        let mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        let dd = String(date.getDate()).padStart(2, '0');
        let hh = String(date.getHours()).padStart(2, '0');
        let min = String(date.getMinutes()).padStart(2, '0');
        let ss = String(date.getSeconds()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`;
      },




      // 新增
      insert() {
        this.form.createBy = getToken();
        this.form.createDate = this.formatDate(new Date());

        add(this.form).then(res => {
          if (res.code == '201') {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          console.error(err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },
      // 修改
      edit() {
        this.form.modifyBy = localStorage.getItem('uId');
        this.form.modifyDate = new Date();
        update(this.form).then(res => {
          if (res.code == '201') {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        }).catch(err => {
          console.error(err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },
      // 提交数据
      save_btn() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.id != '') {
              this.edit();
            } else {
              this.insert();
            }
            this.dialog = false;

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    }
  }
</script>
